# -*- coding:utf-8 -*-
from django.shortcuts import *
from django.shortcuts import render_to_response
from django import forms
from django.http import HttpResponse, JsonResponse
from apps.models import *

class UserForm(forms.Form):
    username = forms.CharField()
    filename = forms.FileField()

def uploadfile(request):
    if request.method == 'POST':
        form = UserForm(request.POST, request.FILES)
        if form.is_valid():
            # 获取表单数据
            username = form.cleaned_data['username']
            filename = form.cleaned_data['filename']
            nav = request.POST.get("nav")
            n = navigation.objects.filter(nav=nav).first()
            print(n)
            if n:
            # 获取数据库数据
                user = photos()
                user.photo = username
                user.filename = filename
                user.nid = n
                user.save()
                return HttpResponse('上传成功')
            else:
                return HttpResponse('上传失败')
    else:
        form = UserForm()
        nav = navigation.objects.all()
    return render_to_response('uploadfile.html', {
        'form': form,
        'nav':nav
    })

def show(request):
    if request.method=='GET':
        nav = navigation.objects.all()
        return render(request,'show.html',{
            'nav':nav
        })
    else:
        check = request.POST.get('data')
        check = int(check)
        nav = navigation.objects.all()
        print(nav)
        for n in nav:
            print(type(n.id))
            if n.id == check:
                print('jjjjjjj')
                x = photos.objects.filter(nid=check).all()
                print(x)
                list=[]
                for i in x:
                    data={
                        'id':i.id,
                        'photo':i.photo,
                        'filename':i.filename
                    }
                    list.append(data)
                    print(list)
                return render(request,'show.html',{
                    'list':list
                })